//获取应用实例
const app = getApp();
const common = require('./../../../utils/common.js');
const utils = require('./../../../utils/util.js');

 

Page({
    data: {
        rowIndex: null,
        rowItem: null,
        colorShow: false,
        colors: [],
        colorName: "",
        allColors: [],
        colorMainActiveIndex: 0,
        colorChecked: [],
        productId: 0, // 款式ID
        pdSpuInfo: {}, //  编辑时，详情信息ID 
        dictGroup: {
            productType: [], // 产品类型  
        },
        attrList: [], // 属性配置列表
        skuListMap: [], // 编辑时，需要匹配旧的数据
        // 属性下拉选择选中的文本值
        attr_sel_text: {},
        userInfo: {}, // 个人信息 
        brandList: [], // 品牌列表
        sel_text: {
            design_user: '', // 设计师
            productType: '', // 产品类型 
            brand: '' // 品牌名称
        },
        sourTypeText: [], //  货源 类型的选中文本
        gsourceTypeList: [], // 货源类型
        tempFiles: [], // 图片原文件
        deleteActionsheet: false,
        now_action_index: -1,
        uploadFile: [], // 上传图片
        formData: {

            designerId: 0, // 设计师id
            belongDepartmentId: 0, // 归属部门id , 必填 /ums/user/user/infoById/${userId} 选择设计师后获取
            belongDepartmentName: "", // 归属部门id , 必填 /ums/user/user/infoById/${userId} 选择设计师后获取

            // /api/ums/user/user/info/v2
            chooseDepartmentId: 0, // 开款部门id，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿
            chooseDepartmentName: '', // 开款部门名称，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿

            chooseUserId: 0, // 开款人id，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿
            chooseUserName: '', // 开款人，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿

            brandId: 0, // 品牌id ,必填
            extensionCode: '', //扩展码
            imageList: [], // 品图片 ,必填 图片 先拿bamboo/baseDictionary/queryByGroupIdentification/imageCategory 全部标签 再调ttp://183.6.58.164:20001/api/bamboo/baseDictionary/queryByGroupIdentification/imageCategory/7/imageLabel 拿标签再调public/oss/original/uploadFace OSS接口拿url

            isSubmit: 1, // 是否提交 1-是 0-否 ,必填 1 是提交 0是保存
            isSubmitOrSave: 1, // 是否提交/保存（1 提交，0 保存）
            operateType: 3, // ,必填 默认传3 1=存为草稿，2=提交编辑，3=提交审核 后端用：
            // 4==表示改操作不是产品发布页面和领取编辑页面中的领取操作,是不会触发设置审核信息和测试信息，更新操作清楚,3是会触发操作 
            productNo: '', // 助记码
            productGoods: '', // 简码 
            productSupplyType: 0, //供货方式（来源于数据字典 group_identification：productSupplyType；1：现货；2：OEM；3：ODM；） , 必填 产品类型下拉框得到
            productType: 0, //产品类型（来源于数据字典group_identification：productType; 0：线上款；1：合作供应商；2：扒图款；3：设计款；4：ODM；） ,必填 产品类别，目前固定传4
            supplyPrice: 0, // 供货单价，必填 供货价 
            specAttributeInfoList: [], // specAttributeInfoList
            specAttributeList: [], // specAttributeList
            supplierCode: '', // 供应商code
            supplierId: '', // 供应商id
            title: '', //
            developRequire: '', // 备注
            designDescription: '', // 卖点
            categoryId: 0, // 品类ID 
        },
        // *图片上传信息
        uploadImageInfo: {
            cateId: 0,
            labelId: 0,
        },
        // 颜色属性列表
        colorAtList: [{
            colorName: '', // 颜色名称
            colorId: '',
            colorMulIndex: [-1, -1],
            color: {},
            isDefault: 1, 
        }], // 货源数据  
        // *商品分类
        cate_show_data: [],
        cate_all_data: [],
        sel_cate_arr: [0, 0, 0],
        choose_cate_index_arr: [0, 0, 0],
        choose_cate_id_arr: [0, 0, 0], 
        skuAttrs: [], // sku的属性信息,为了组装数据
        // *颜色
        color_mul_index: [-1, -1],
        color_tree: {}, // 颜色 
        color_mul_arr: [],
        colorMulPArr: [], // 颜色下拉的第一个数组 
        // *尺码组 
        sizeGroupInfo: {}, // 选中的尺码组信息
        sizeGroupId: 0, // 选中的尺码组id
        size_groups: [], // 尺码组列表
        // 尺码 
        size_tree: [], // 尺码树
        curSizeList: [], // 当前尺码列表
        selectedSizes: [], // 选中的尺码ID集合
        selectedColors: [], // 选中的颜色集合 
        // 根据颜色+尺码 组装的sku列表
        skuList: [],
        // *货源
        sourceList: [{
            typeName: '',
            goodsSourceType: 0,
            supplierId: 0,
            supplierCode: '',
            supplierName: '',
            productSource: '',
            isDefault: 1,
            isUrlName: false,
            deleted: false,
        }], // 货源数据 
        chooseSupplierIndex: -1,
        isShowSup: false, // 选择供应商
        // *供应商
        supplierPageConfig: {
            current: 1,
            size: 20,
            pages: 0,
        }, // 选择供应商请求配置
        supplierList: [], // 供应商列表 
    },

    onLoad: async function (options) {
      this.listTreeColor()
        // 设置标题
        wx.setNavigationBarTitle({
            title: '创建款式'
        });
        this.queryDict() // 字典
        this.getGoodsSourceType()
        await this.getUploadImageInfo()
        this.getUserInfo()
        this.apCateList(); // 分类列表
        this.apDesigner() //   设计师列表
        this.getBrandList() //  品牌
        this.getSupplierList()
        this.getColorTree() // 颜色

        //  编辑  productId
        if (options.productId != undefined && options.productId > 0) {
            // 重设标题
            wx.setNavigationBarTitle({
                title: '编辑款式'
            });
            this.setData({
                productId: options.productId
            });
            this.getPdSpuDetailById();
        }
    },

    // 获取样板详情
    getPdSpuDetailById: function () {
        const that = this
        const productId = that.data.productId
        common.request_api(`/api/bamboo/PdPublish/getPdSpuDetailById/${productId}/false`, {

        }, true, 'GET').then(async res => {
            const data = res.data
            // 获取设计师的名称
            common.request_api(`/api/ums/user/user/infoById/${data.designerId}`, {}, true, 'get').then(designerRes => {
                if (designerRes.code == 200) {
                    that.setData({
                        [`sel_text.design_user`]: designerRes.data.personName,
                    });
                }
            })
            // 货源信息 
            common.request_api(`/api/bamboo/baseSourceManagement/getBaseSourceManagementsByProductNo`, {
                productNo: data.productNo
            }, true, 'get').then(gsRes => {
                if (gsRes.code == 200) {
                    const gsourceTypeList = that.data.gsourceTypeList 
                    let sourceList = []
                    gsRes.data.forEach(item => {
                        const gstData = gsourceTypeList.find(gstItem => gstItem.id == item.goodsSourceType);
                        item.typeName = gstData.name || ''
                        sourceList.push(item);
                    });
                    that.setData({
                        sourceList: gsRes.data,
                    });
                }
            })
            // 属性值显示 attr_sel_text attributeId
            let attrSelText = {}
            let attributeValueListMap = {} // 属性 key=>value 字典
            data.attributeValueList.forEach(item => {
                attrSelText[item.attributeId] = item.attributeValueIdsValue
                attributeValueListMap[item.attributeId] = item
            }); 
            await that.getCateAttrByCId(data.categoryId, attributeValueListMap) 
            that.loadDetailByCId(data.categoryId)
            await that.getSizeByCId(data.categoryId)
            // 图片  
            let uploadFile = []
            data.imageList.forEach(item => {
                let fullUrl = `${app.globalData.alphaCdnUrl}/${item.image}`
                uploadFile.push({
                    "id": item.id,
                    "spuId": item.spuId,
                    "image": item.image, 
                    "url": fullUrl,
                    "fileName": fullUrl,
                    "accessoryUrl": fullUrl, 
                    "imageCategory": item.imageCategory, // 7
                    "accessoryCategoryCode": that.data.uploadImageInfo.cateId, // 7
                    "sourceTypeCode": "1",
                    "imageType": item.imageType, // 16
                    "imageLabel": item.imageLabel, // 16
                    "accessoryTypeCode": that.data.uploadImageInfo.labelId, // 16

                    "deleted": item.deleted,
                    "isBody": item.isBody,
                    "isMain": item.isMain,
                    "skuId": item.skuId,
                    "sort": item.sort || 0,
                    "color": item.color || '',

                });

            }); 
            let colorAtList = []
            let selectedSizes = []
            let sizeGroupId = '' // 尺码组ID
            let sizeGroupName = '' // 尺码组名称
            let curSizeList = [] // 尺码列表
            data.specAttributeInfoList.forEach(item => { 
                if (item.specAttributeName == "颜色") {
                    item.specAttributeValueList.forEach(speAttrValitem => {
                        colorAtList.push({
                            colorName: speAttrValitem.name, // 颜色名称
                            colorId: speAttrValitem.specAttributeValueId,
                            colorMulIndex: [-1, -1],
                            color: {},
                            isDefault: 1,
                        });
                    })
                }

                if (item.specAttributeName == "尺码") {
                    sizeGroupId = item.specAttributeCategoryId
                    sizeGroupName = item.specAttributeCategoryName 
                    item.specAttributeValueList.forEach(speAttrValitem => {
                        selectedSizes.push(speAttrValitem.specAttributeValueId);
                    })
                }
            });
            let sizeGroupInfo = {} // 选中的尺码组信息
            that.data.size_groups.forEach(sgItem => {
                if (sgItem.id == sizeGroupId) { 
                    sizeGroupInfo = sgItem
                    sgItem.children.forEach(sgChItem => {
                        sgChItem.isChecked = 0;
                        if (selectedSizes.includes(sgChItem.id)) {
                            sgChItem.isChecked = 1;
                        }
                        curSizeList.push(sgChItem);
                    })
                }
            })

            // 产品类型 回显 
            let productTypeText = "" 
            that.data.dictGroup.productType.forEach(tempItem => {
                if (tempItem.value == data.productType) { 
                    productTypeText = tempItem.name
                }
            })

            // skuList 数据的处理
            let skuListMap = {} // 属性 key=>value 字典
            data.skuList.forEach(tempItem => {
                let skuListKey = `${tempItem.skuDesc}` // skuDesc
                skuListMap[skuListKey] = tempItem
            })
            // 选中的尺码信息   

            that.setData({
                pdSpuInfo: data, // 编辑时，详情信息
                attr_sel_text: attrSelText, // 属性值显示
                uploadFile: uploadFile, // 图片
                colorAtList: colorAtList, // 颜色
                selectedSizes: selectedSizes, //  
                sizeGroupInfo: sizeGroupInfo,
                curSizeList: curSizeList, // 尺码列表 
                [`sizeGroupId`]: sizeGroupId,
                [`sel_text.size_group`]: sizeGroupName, // 显示名称 
                [`sel_text.choose_cate_name`]: data.classificationText,

                [`sel_text.productType`]: productTypeText,
                skuListMap: skuListMap, // sku-map

                [`formData.designerId`]: data.designerId,
                [`formData.chooseDepartmentId`]: data.chooseDepartmentId, // 开款部门id
                [`formData.chooseDepartmentName`]: data.chooseDepartmentName, // 开款部门名称id
                [`formData.chooseUserId`]: data.chooseUserId, // 开款人id
                [`formData.chooseUserName`]: data.chooseUserName, // 开款人姓名
                [`formData.belongDepartmentId`]: data.belongDepartmentId, // 归属部门id
                [`formData.belongDepartmentName`]: data.belongDepartmentName, // 归属部门id

                [`formData.brandId`]: data.brandId, // 品牌id ,必填
                [`formData.extensionCode`]: data.extensionCode, //   扩展码
                [`formData.productNo`]: data.productNo, //   助记码
                [`formData.productGoods`]: data.productGoods, //   简码
                [`formData.productSupplyType`]: data.productSupplyType, //   供货方式
                [`formData.productType`]: data.productType, //    产品类型
                [`formData.supplyPrice`]: data.supplyPrice, //    供货单价，必填 供货价

                [`formData.title`]: data.title, //     title
                [`formData.developRequire`]: data.developRequire, //     备注
                [`formData.designDescription`]: data.designDescription, //       卖点
                [`formData.categoryId`]: data.categoryId, //     品类ID
                [`formData.supplierCode`]: data.supplierCode, //    供应商code 
                [`formData.supplierId`]: data.supplierId, //     供应商

                [`formData.specAttributeList`]: data.specAttributeList, //     specAttributeList
                [`formData.specAttributeInfoList`]: data.specAttributeInfoList, //     specAttributeInfoList 
            }); 
            that.rebuildSkuList() 
        });
    },

    // 尺码选择器
    sizeBindChange(e) { 
        const selectedValues = e.detail.value; 
        this.setData({
            selectedSizes: selectedValues
        });
        this.rebuildSkuList() 
    },
    // 清除选中的尺码
    clearSelection: function () { 
        this.setData({
            selectedSizes: []
        });
        this.rebuildSkuList()
    },

    // 尺码组选择器
    sizeGroupBindChange: function (e) {
        const idx = e.detail.value
        let curSizeList = []
        let selectedSizes = []  // 选中的尺码的值['aa','bb']
        this.data.size_tree[idx].children.forEach(item => { 
            item.isChecked = 1 // 界面默认全部选中
            curSizeList.push(item);
            selectedSizes.push(item.value);
        }); 
        this.clearSelection() // 清除之前选中的尺码  "1498560369751232514"
        this.setData({
            curSizeList: curSizeList, // 尺码列表
            selectedSizes: selectedSizes, // 尺码列表
            [`sizeGroupInfo`]: this.data.size_groups[idx], // 选中的尺码组信息
            [`sizeGroupId`]: this.data.size_groups[idx].id,
            [`sel_text.size_group`]: this.data.size_groups[idx].name, // 显示名称
        });
        this.rebuildSkuList() // 选中的尺码，需要重新组装sku
    },

    // 选择供应商
    chooseSupplier: function (events) {
        const index = events.currentTarget.dataset.index; 
        this.setData({
            isShowSup: true,
            chooseSupplierIndex: index, // 辅助 货源index的供应商
        })
    },

    // 关闭半屏
    closeSupHalf: function (e) {
        this.setData({
            isShowSup: false,
        })
    },

    // 确认选中 供应商  
    surchooseSupplier: function (events) {
        const dataset = events.currentTarget.dataset;
        const index = dataset.index; // 供应商列表index 
        let chooseSupplierIndex = this.data.chooseSupplierIndex
        let sourceList = this.data.sourceList
        sourceList[chooseSupplierIndex].supplierId = dataset.id // 供应商ID
        sourceList[chooseSupplierIndex].supplierName = dataset.supname // 供应商名称
        sourceList[chooseSupplierIndex].supplierCode = dataset.supcode // 供应商名称
        this.setData({
            sourceList: sourceList,
            isShowSup: false,
            chooseSupplierIndex: -1,
        });
    },

    // 增加供应商
    addSupplier: function () {
        let sourceList = this.data.sourceList
        let item = {
            typeName: '',
            goodsSourceType: 0,
            supplierId: 0,
            supplierCode: '',
            supplierName: '',
            productSource: '',
            isDefault: 0,
            isUrlName: false,
            deleted: false,
        } 
        sourceList = sourceList.concat(item) 
        this.setData({
            sourceList: sourceList,
        }); 
    },

    // 删除供应商
    delSupplier: function (events) {
        const index = events.currentTarget.dataset.index;
        let sourceList = this.data.sourceList
        if (sourceList.length <= 1) {
            wx.showToast({
                title: '至少保留一个',
                icon: 'error',
                duration: 2000,
            });
            return false
        } 
        sourceList.splice(index, 1); 
        this.setData({
            sourceList: sourceList,
        });
    },

    // 默认货源供应商
    radioChange(e) {
        const val = e.detail.value
        const items = this.data.sourceList
        for (let i = 0, len = items.length; i < len; ++i) {
            items[i].isDefault = i == val ? 1 : 0
        }
        this.setData({
            sourceList: items
        })
    },


    // 颜色属性

    // 增加 
    addColorAt: function () {
        let colorAtList = this.data.colorAtList
        let item = {
            colorName: '', // 颜色名称
            colorId: '',

            colorMulIndex: [-1, -1],
            color: {},
            isDefault: 1,

        }
        colorAtList = colorAtList.concat(item) 
        this.setData({
            colorAtList: colorAtList,
        }); 
        this.rebuildSkuList()
    },

    // 删除颜色
    delColorAt: function (events) {
        const index = events.currentTarget.dataset.index;
        let colorAtList = this.data.colorAtList
        if (colorAtList.length <= 1) {
            wx.showToast({
                title: '至少保留一个',
                icon: 'error',
                duration: 2000,
            });
            return false
        } 
        colorAtList.splice(index, 1); 
        this.setData({
            colorAtList: colorAtList,
        });
        this.rebuildSkuList()
    },

    // 货源类型 sourTypeText
    goodsSourTypeChange: function (e) {
        const data = this.data.gsourceTypeList[e.detail.value]
        const dataset = e.currentTarget.dataset;
        let sourceList = this.data.sourceList
        sourceList[dataset.index].goodsSourceType = data.id
        sourceList[dataset.index].typeName = data.name
        this.setData({
            sourceList: sourceList,
        });
    },

    // 颜色选择器
    colorBindMulPChange: function (e) {
        const idA = e.detail.value[0]
        const idB = e.detail.value[1]
        const dataset = e.currentTarget.dataset
        let colors = this.data.color_tree[idA].children 
        const sColor = colors[idB]
        const sIdArr = this.data.colorAtList.find(item => item.colorId === sColor.id);
        if (sIdArr != undefined && sIdArr) {
            wx.showToast({
                title: `${sColor.name}颜色已存在！`,
                icon: 'error',
                duration: 3000
            })
            return false
        } 
        let selColors = []
        selColors.push(sColor)
  console.log(selColors,'selColors');
        this.setData({
            // "color_mul_index[0]": idA, // 颜色一层ID
            // "color_mul_index[1]": idB, // 颜色二层ID
            selectedColors: selColors, // 选中的颜色 
            [`colorAtList[${dataset.index}].colorMulIndex[0]`]: idA,
            [`colorAtList[${dataset.index}].colorMulIndex[1]`]: idB,
            [`colorAtList[${dataset.index}].colorName`]: sColor.name,
            [`colorAtList[${dataset.index}].color`]: sColor,
            [`colorAtList[${dataset.index}].colorId`]: sColor.id,
            // [`colorAtList[${dataset.index}].parentId`] :  sColor.parentId, 

        }) 
        console.log(this.data.colorAtList);
        this.rebuildSkuList()
    },

    // 颜色选择器列改变
    colorBindMulPColChange: function (e) {
        const that = this
        const dataset = e.currentTarget.dataset 
        switch (e.detail.column) {
            case 0:
                let idx = e.detail.value
                let childrens = that.data.color_tree[idx].children
               
                let color_twos = []
                childrens.forEach(item => {
                    color_twos.push(item.name);
                });
                that.setData({
                    "color_mul_arr[1]": color_twos, 
                    // "color_mul_index[0]": e.detail.value, 
                    // "color_mul_index[1]": 0, parentId 
                    [`colorAtList[${dataset.index}].colorMulIndex[0]`]: e.detail.value,
                    [`colorAtList[${dataset.index}].colorMulIndex[1]`]: 0,
                })

        }
    },

    colorSwitchChange: function (e) {
        const that = this
        const dataset = e.currentTarget.dataset 
        that.setData({
            [`colorAtList[${dataset.index}].isDefault`]: e.detail.value ? 1 : 0,

        })
    },
 
    // 颜色选择器
    colorBindMulPickerChange: function (e) {
        const idA = e.detail.value[0]
        const idB = e.detail.value[1]

        let colors = this.data.color_tree[idA].children
         
        let selColors = []
        selColors.push(colors[idB]) 
        //   [`formData.brandId`]: id,
        this.setData({
            "color_mul_index[0]": idA, // 颜色一层ID
            "color_mul_index[1]": idB, // 颜色二层ID
            selectedColors: selColors, // 选中的颜色

        })

    },

    // 颜色选择器列改变
    colorBindMulPickerColChange: function (e) {
        const that = this
      
        switch (e.detail.column) {
            case 0:
                let idx = e.detail.value
                let childrens = that.data.color_tree[idx].children
               
                let color_twos = []
                childrens.forEach(item => {
                    color_twos.push(item.name);
                });
                that.setData({
                    "color_mul_arr[1]": color_twos,
                    "color_mul_index[0]": e.detail.value,
                    "color_mul_index[1]": 0,

                })

        }
    },

    // 供应商
    getSupplierList: function (is_search = 0) {
        const that = this
        let supplierPageConfig = that.data.supplierPageConfig
        // 发起请求
        const result = common.request_api('/api/erp/mdSupplier/querySupplierListPage', {
            // page: __this.data.factory_page + 1,
            // quick_search: __this.data.factory_keywords,
            // limit: 100,
            needPage: true,
            current: supplierPageConfig.current,
            size: supplierPageConfig.size,
            pages: supplierPageConfig.pages,
            selectParameter: {
                supplierCodes: null,
                supplierFirstTypeList: ["finishedProduct"],
                buyerId: "",

            },
            parame: [],
            selectParame: [],
            orderBy: "",



        }, false);

        // {
        // 	"needPage": true,
        // 	"current": 1,
        // 	"size": 10,
        // 	"pages": 0,
        // 	"selectParameter": {
        // 		"supplierCodes": null,
        // 		"supplierFirstTypeList": ["finishedProduct"],
        // 		"isEnable": "1",
        // 		"buyerId": ""
        // 	},
        // 	"parame": [],
        // 	"selectParame": [],
        // 	"orderBy": ""
        // }

        result.then(res => { 
            let supplierList = that.data.supplierList 
            if (res.data.records) { 
                supplierList = supplierList.concat(res.data.records) 
                // let newArr = arr1.concat(arr2); 
                that.setData({
                    "supplierList": supplierList, 
                }) 
            }

        });
    },

    // 设计师列表
    apDesigner: function () {
        const result = common.request_api('/api/ums/positionDuty/queryDropUserByDutyCode/designer', {}, false, 'get');
        // 使用reduce来分组   
        result.then(res => {
            this.setData({
                designList: res.data,
            });
        });
    },

    // 货源类型 gsourceTypeList getGoodsSourceType
    getGoodsSourceType: function () {
        const result = common.request_api('/api/erp/baseDictionary/queryByGroupIdentification/goodsSourceType', {}, false, 'get'); 
        result.then(res => {
            this.setData({
                gsourceTypeList: res.data,
            });
        });
    },


    getBrandList: function () {
        const result = common.request_api('/api/bamboo/sysBrand/queryListVo', {}, false, 'get');

        result.then(res => {
            const id = res.data[0].id;
            const name = res.data[0].name;
            this.setData({
                [`formData.brandId`]: id,
                [`sel_text.brand`]: name,
                brandList: res.data,
            });
        });
    },

    // 获取尺码
    getSizeByCIbbd: async function (cateId) {
        // 发起请求
        return new Promise((resolve, reject) => {
            common.request_api('/api/bamboo/pdSpecAttribute/listTree', {
                categoryId: cateId
            }, false, 'GET').then(res => { 
                const data = res.data
                const map = {};
                data.forEach(item => {
                    map[item.id] = item;
                });
                // 分别处理第一层和第二层元素
                const firstLayer = []; // 带children层级
                const secondLayer = [];
                let size_groups = [];
                data.forEach(item => {
                    if (item.parentId === '0') {
                        size_groups.push(item);
                        firstLayer.push(item);
                    } else {
                        secondLayer.push(item);
                    }
                });
                // 将第二层元素添加到对应的第一层元素的 children 数组中
                secondLayer.forEach(item => {
                    const parent = map[item.parentId];
                    if (parent) {
                        parent.children.push(item);
                    }
                }); 
                this.setData({
                    size_groups: size_groups, // 尺码组 
                    size_tree: firstLayer
                });
                resolve(size_groups); // 解析成功的结果
            }).catch(error => { 
                reject(error); // 拒绝并传递错误
            })
        });
    },

    // 获取属性 
    getCateAttrByCId: async function (cateId, attributeValueListMap = {}) {
        let that = this
        return new Promise((resolve, reject) => { 
            common.request_api('/api/bamboo/pdCategoryAttribute/list', {
                productCategoryId: cateId
            }, false, 'GET').then(res => {
                // 处理数据 ， 把 res.data 元素中的 attributeCategoryId 值为key 
                var attr = res.data.reduce(function (acc, item) {
                    // let valArr = attributeValueListMap[item.attributeId] !== undefined ? attributeValueListMap[item.attributeId] : [],
                    item.value = ''
                    let attributeId = item.attributeId
                    if (attributeValueListMap[attributeId] != undefined && attributeValueListMap[attributeId]) {
                        let valArr = attributeValueListMap[attributeId].attributeValueIds
                        if (attributeValueListMap[attributeId].attributeType === '2') {
                          item.value = attributeValueListMap[attributeId].attributeValue
                        }else if (valArr.length > 0) {
                            item.value = valArr.join(',');
                        }
                    } 
                    // 处理默认值
                    if(item.defaultValue !== null &&  item.defaultValue !== ''){
                        if(item.attributeType == 1){  // 下拉选择   
                            item.value = item.defaultValue
                            const artrSelText = item.attributeValueList.find(attrItem => attrItem.id === item.defaultValue)?.value; 
                            that.setData({
                                [`attr_sel_text.${attributeId}`]: artrSelText , // 显示文本
                            }); 
                        }else if(item.attributeType == 2){  // 输入文本  
                            item.value = item.defaultValue
                        }
                    } 
                    acc[attributeId] = item; // attributeId  attributeCategoryId
                    return acc;
                }, {});
                if (Object.keys(attributeValueListMap).length === 0) {
                    console.log('对象为空');
                } else {
                    console.log('对象不为空');
                } 
                this.setData({
                    attrList: attr
                });
                resolve(true); // 解析成功的结果
            }).catch(error => {
                console.error("获取属性失败:", error);
                reject(error); // 拒绝并传递错误
            })
        });

    },

    // 获取产品规格属性信息
    loadDetailByCId: function (cateId) {
        // 发起请求
        let url = `/api/bamboo/pdCategoryRelateSpecAttributeCategory/loadDetail/${cateId}`
        const result = common.request_api(url, {}, true, 'GET');
        result.then(res => {
            // 处理数据 ， 把 res.data 元素中的 attributeCategoryId 值为key 
            // var attr = res.data.reduce(function(acc, item) { 
            //     acc[item.attributeCategoryId] = item;
            //     return acc;
            // }, {});  
            this.setData({
                skuAttrs: res.data
            });
        });
    },




    // 个人信息
    getUserInfo: function () {
        const result = common.request_api('/api/ums/user/user/info/v2', {}, false, 'GET');
        result.then(res => {
            this.setData({
                userInfo: res.data
            });
        });
    },

    queryDict: function () {
        // 发起请求
        const result = common.request_api('/api/bamboo/commonDictionary/queryCommonDictionaryByGroups', [
            'productType', 'productSupplyType'
        ], false, 'POST');
        result.then(res => {
            const group = res.data.reduce((acc, item) => {
                if (!acc[item.groupIdentification]) {
                    acc[item.groupIdentification] = []; // 如果累积对象中还没有这个groupIdentification的键，则初始化它为一个空数组  
                }
                acc[item.groupIdentification].push(item); // 将当前对象添加到对应的组中  
                return acc; // 返回累积对象供下一次迭代使用  
            }, {});
            // 另外处理数据， 获取  groupIdentification = productSupplyType and name = 正常款 返回 item.value 的值
            const productTypeData = group.productSupplyType.find(item => item.name === '正常款');
           
            const productTypePid = productTypeData.value;
            // 获取  groupIdentification = productType and parentId = productTypePid 的列表
            const productTypeList = group.productType.filter(item => item.parentId === productTypePid);
            group.productType = productTypeList;
            this.setData({
                dictGroup: group,
                [`formData.productSupplyType`]: productTypeData.value,
            });
        });
    },

    // 获取上传图片信息
    getUploadImageInfo: async function () {
        return new Promise((resolve, reject) => {
            // 发起请求
            common.request_api('/api/bamboo/baseDictionary/queryByGroupIdentification/imageCategory', {

            }, true, 'GET').then(async res => {
                const data = res.data
                let cateId = 0
                let labelId = 0
                data.forEach(item => {
                    if (item.name == '样板图片') {
                        cateId = item.id
                        // const url = `/api/bamboo/baseDictionary/queryByGroupIdentification/imageCategory/${cateId}/imageLabel`
                        // const labelRes = common.request_api(url, {}, true, 'GET');
                        // labelRes.then(laRes => {
                        //     laRes.data.forEach(labelItem => {
                        //         if (labelItem.name == '列表主图') {
                        //             labelId = labelItem.id
                        //         }
                        //     })
                        // })
                    }
                });
                const url = `/api/bamboo/baseDictionary/queryByGroupIdentification/imageCategory/${cateId}/imageLabel`
                const laRes = await common.request_api(url, {}, true, 'GET');
                laRes.data.forEach(labelItem => {
                  if (labelItem.name == '列表主图') {
                      labelId = labelItem.id
                  }
                })
                this.setData({
                    uploadImageInfo: {
                        cateId: cateId,
                        labelId: labelId,
                    },
                });
                resolve(true);
            }).catch(error => {
                console.error("error:", error);
                reject(error);
            })

        })
    },

    // 获取颜色
    getColorTree: function () {
        // 发起请求
        const result = common.request_api('/api/bamboo/sysColor/listTree', {}, false, 'GET');
        result.then(res => {
            // 处理数据 ， 把 res.data 
            const data = res.data
            // 创建一个 map 用于存储所有元素
            const map = {};
            // 遍历原始数据，将每个元素以 id 作为键存入 map 中
            data.forEach(item => {
                map[item.id] = item;
            });
            // 分别处理第一层和第二层元素
            const firstLayer = []; // 带children层级
            const secondLayer = [];
            let color_ones = [];
            data.forEach(item => {
                if (item.parentId === '0') {
                    color_ones.push(item.name);
                    firstLayer.push(item);
                } else {
                    secondLayer.push(item);
                }
            });
            // 将第二层元素添加到对应的第一层元素的 children 数组中
            secondLayer.forEach(item => {
                const parent = map[item.parentId];
                if (parent) {
                    parent.children.push(item);
                }
            });
            const def_childrens = res.data[0].children;
            let color_twos = []
            def_childrens.forEach(item => {
                color_twos.push(item.name);
            });
          
            this.setData({
                color_tree: firstLayer,
                colorMulPArr: color_ones,
                color_mul_arr: [color_ones, color_twos]
            });
        });
    },

    // 获取尺码 
    getSizeByCId: async function (cateId) {
        // 发起请求
        return new Promise((resolve, reject) => {
            common.request_api('/api/bamboo/pdSpecAttribute/listTree', {
                categoryId: cateId
            }, false, 'GET').then(res => {
                const data = res.data
                const map = {};
                data.forEach(item => {
                    map[item.id] = item;
                });
                // 分别处理第一层和第二层元素
                const firstLayer = []; // 带children层级
                const secondLayer = [];
                let size_groups = [];
                data.forEach(item => {
                    if (item.parentId === '0') {
                        size_groups.push(item);
                        firstLayer.push(item);
                    } else {
                        secondLayer.push(item);
                    }
                });
                // 将第二层元素添加到对应的第一层元素的 children 数组中
                secondLayer.forEach(item => {
                    const parent = map[item.parentId];
                    if (parent) {
                        parent.children.push(item);
                    }
                });
                this.setData({
                    size_groups: size_groups, // 尺码组 
                    size_tree: firstLayer
                });
                resolve(size_groups); // 解析成功的结果
            }).catch(error => {
                console.error("获取尺码组失败:", error);
                reject(error); // 拒绝并传递错误
            })
        });
    },

    // 获取分类
    apCateList: function () { 
        const result = common.request_api('/api/bamboo/pdCategory/list', { 
        }, false, 'GET');
        result.then(res => { 
            // 根据列表转树 
            let cate_all_data = utils.listToTree(res.data) 
            this.setData({
                cate_show_data: [cate_all_data, cate_all_data[0].children || [], cate_all_data[0].children[0].children || []],
                cate_all_data: cate_all_data
            }); 
        });
    },

    // 属性下拉单选
    caAttrChange: function (e) {
       
        const index = e.detail.value; // 获取当前选中的索引
        const pickerId = e.currentTarget.dataset.id; // 如果你在 picker 上绑定了自定义数据 id
        const itemName = e.currentTarget.dataset.name; // 或者绑定其他自定义数据用于识别 
      
        // attr_sel_text attrList
        const list = this.data.attrList[pickerId].attributeValueList;
        this.data.attrList[pickerId].value = list[index].id // 保存选中的值
        this.setData({
            [`attr_sel_text.${pickerId}`]: list[index].value,
        });
    },

    // 属性输入
    caAttrInputChange(e) {
        const {  field  } = e.currentTarget.dataset
        this.data.attrList[field].value = e.detail.value.trim() // 保存选中的值
    },

    designChange: function (e) {
        const uid = this.data.designList[e.detail.value].id
        this.setData({
            [`formData.designerId`]: uid,
            [`sel_text.design_user`]: this.data.designList[e.detail.value].name,
        });
        // 获取部门ID
        this.getDesignDepId(uid)
    },

    brandChange: function (e) {
        const id = this.data.brandList[e.detail.value].id
        this.setData({
            [`formData.brandId`]: id,
            [`sel_text.brand`]: this.data.brandList[e.detail.value].name,
        });
    },


    // 产品类型
    productTypeChange: function (e) {
        let data = this.data.dictGroup.productType[e.detail.value]
        this.setData({
            [`formData.productType`]: data.value,
            [`sel_text.productType`]: data.name,
        });
    },


    // 输入框改变
    formInputChange(e) {
        const {
            field
        } = e.currentTarget.dataset
        this.setData({
            [`formData.${field}`]: e.detail.value.trim()
        }); 
    },

    // 获取设计师部门ID
    getDesignDepId(uid) {
        const result = common.request_api(`/api/ums/user/user/infoById/${uid}`, {}, true, 'get');
        result.then(res => {
            
            if (res.code == 200) {
                this.setData({
                    [`formData.belongDepartmentId`]: res.data.organizationalId,
                    [`formData.belongDepartmentName`]: res.data.organizationalName,
                });
            }
        }).finally(() => {

        })
    },

    // 组装sku列表 colorAtList curSizeList
    rebuildSkuList() {
        const that = this 
        let skuList = []; // 组装 sku
        let sort = 1; 
        that.data.colorAtList.forEach(cItems => {
            that.data.selectedSizes.forEach(sizeId => {  
                let sizeObj = that.data.curSizeList.find(item => item.id == sizeId)
                let skuDesc = `${cItems.colorName},${sizeObj.name}`
                let linkSkuItem = {}
                // 查找是否有编辑带过来的sku 列表
                if (that.data.skuListMap[skuDesc] !== undefined && that.data.skuListMap[skuDesc]) {
                    linkSkuItem = that.data.skuListMap[skuDesc]
                } 
                skuList.push({
                    "id": linkSkuItem.id || '',
                    "image": linkSkuItem.image || '', 
                    "isGroup": linkSkuItem.isGroup || false, // 是否组合sku ,必填 默认 false
                    "isSample": linkSkuItem.isSample || 0, // 审版SKU，0：默认否，1：是 ,必填 默认0
                    "isSplit": linkSkuItem.isSplit || false, // 是否可拆分发 ,必填 默认 false  
                    "skuGroupInfoList": linkSkuItem.skuGroupInfoList || [], //  组合sku信息 数组  
                    "sort": linkSkuItem.sort || sort,
                    "spuId": linkSkuItem.spuId || '',
                    "stock": linkSkuItem.stock || '', 
                    // "isGroup":linkSkuItem.image || '',
                    // "isSample":linkSkuItem.image || '',
                    // "isSplit":linkSkuItem.image || '', 
                    // spuId 
                    "颜色尺码": `${cItems.colorName}，${sizeObj.name}，`, // 名称 "紫灰，29，" 
                    "pdSpecAttributeCategoryId": that.data.sizeGroupId, // 尺码组ID 规格属性分类ID ,必填 我司规格尺码的父级Id
                    "sizeId": sizeId, // 尺码ID
                    "skc": cItems.colorId, // 颜色ID
                    "skcName": cItems.colorName, // SKC名称,必填
                    "skuEnName": cItems.colorName, // sku颜色英文名称 ,必填 
                    "colorCategoryId": cItems.parentId || '', // 颜色是父级ID 
                    "skuDesc": skuDesc, // 紫灰,29 
                    "skuSaleDesc": `${cItems.colorName},${sizeObj.name}`, // 紫灰,29
                    "skuNameDesc": `${that.data.formData.title},${cItems.colorName},${sizeObj.name}`, // "牛仔长裤加厚牛仔长裤,紫灰,29",
                    "skuSaleRelate": `${cItems.colorName},${sizeObj.name}`, // "紫灰,29",
                    "sizeType": sizeObj.description || '', // "165/72A（29）",
                    "sizeName": sizeObj.name || '', // "29",
                    // 供货价
                    "supplyPrice": that.data.formData.supplyPrice || '',
                    "enable": 0, // 启用状态，0：启用，1：作废，默认启用 ,必填 默认0 
                })
                sort = sort + 1
            });
        });
        console.log(skuList,'skuList');
        that.setData({
            skuList: skuList,
        }); 
        // if (skuList.length <= 0) {
        //     wx.showToast({
        //         title: '请先添加尺码和颜色',
        //         icon: 'none',
        //         duration: 2000
        //     })
        //     return false
        // }
        // req_param.skuList = skuList 
    },

    // 提交接口
    formSubmit: function (e) {
        var that = this;
        // 加载条
        wx.showLoading({
            title: '正在提交',
            mask: true
        })
        // 组装sku
        // var sku_arr = [];
        // var color_arr = [];
        // if (that.data.sel_color_list.length > 0) {
        //     that.data.sel_color_list.forEach(function (item, index) {
        //         sku_arr.push({
        //             color: item.name,
        //             quantity: item.num == '' ? 0 : item.num,
        //             delivery_time:item.delivery_time
        //         });
        //         color_arr.push(item.name)
        //     });
        // }
        // 组装图片
        // var template_images = [];
        // if (that.data.uploadFile.length > 0) {
        //     that.data.uploadFile.forEach(function (item, index) {
        //         template_images.push(item.file_key);
        //     });
        // }
        // 重新组装
        const formDataRequired = [{
          prop: 'categoryId',
          label: '货品分类'
        },{
          prop: 'title',
          label: '产品名称'
        },{
          prop: 'productType',
          label: '产品类型'
        },{
          prop: 'brandId',
          label: '品牌'
        },{
          prop: 'imageList',
          label: '图片'
        },{
          prop: 'productGoods',
          label: '简码'
        },{
          prop: 'designerId',
          label: '设计师'
        }]
        let req_param = that.data.formData;
        req_param.imageList = that.data.uploadFile
        const formDataRequiredFind = formDataRequired.find(p => !req_param[p.prop] || (req_param[p.prop] && req_param[p.prop].length === 0))
        if (formDataRequiredFind) {
          wx.showToast({
              title: `请先完善${formDataRequiredFind.label}`,
              icon: 'none',
              duration: 2000
          })
          return
        }
        req_param.id = that.data.productId || ""
        req_param.isSubmitOrSave = that.data.productId ? 0 : 1 //是否提交/保存（1 提交，0 保存）
 
        // 组装 开款人相关
        const userInfo = that.data.userInfo
        req_param.chooseDepartmentId = userInfo.organizationalId || 0 // 开款部门id，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿
        req_param.chooseDepartmentName = userInfo.organizationalName || '' // 开款部门名称，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿
        req_param.chooseUserId = userInfo.id || 0 // 开款人id，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿
        req_param.chooseUserName = userInfo.userName || '' // 开款人，必填 接口/bamboo/sysUserDepartment/getUserDepartmentByUserId/${userId} 通过当前登录人Id来拿

        // 组装 specAttributeList
        
        let sizeListName = []; // 选中的尺码名称
        that.data.curSizeList.forEach(item => {
            // item.id  是否在 that.data.selectedSizes 中
            if (that.data.selectedSizes.includes(item.id)) {
                sizeListName.push(item.name)
            }
        });
        // 选中的颜色名称 
        let specAttributeValueListToColor = []; // 选中的颜色 - 属性  
        let selectedColorName = []; // 选中的颜色  

        that.data.colorAtList.forEach(item => {
            selectedColorName.push(item.colorName)
            specAttributeValueListToColor.push({
                "convertSourceName": item.colorName,
                "name": item.colorName,
                "specAttributeValueId": item.colorId,
                "pdSpecAttributeCategoryId": "",
                //"specAttributeValueId": item.colorId, 
                //"pdSpuSpecAttributeCategoryId": "",

            })
        });

        //      that.data.selectedColors.forEach(item => { 
        //          selectedColorName.push(item.name)
        //          specAttributeValueListToColor.push({
        // 	"convertSourceName": item.name,
        // 	"name": item.name,
        // 	"specAttributeValueId": item.id, 
        // 	"pdSpecAttributeCategoryId": ""
        // })
        //      }); 

        req_param.specAttributeList = [{
            "cnName": "颜色",
            "valueList": selectedColorName // 选中的颜色
        }, {
            "cnName": "尺码",
            "valueList": sizeListName // 选中的尺码名称
        }]
        // 组装 sku   
        // let skuList = []; 

        //       that.data.colorAtList.forEach(cItems => { 

        //           that.data.selectedSizes.forEach(sizeId => {
        //               console.log("选中的颜色",cItems)
        //               console.log("选中的尺码-sizeId",sizeId)
        //               let sizeObj = that.data.curSizeList.find(item => item.id == sizeId)
        //               skuList.push({
        //                   "颜色尺码": `${cItems.colorName}，${sizeObj.name}，`,  // 名称 "紫灰，29，"

        //                   "pdSpecAttributeCategoryId": that.data.sizeGroupId, // 尺码组ID 规格属性分类ID ,必填 我司规格尺码的父级Id
        //                   "sizeId": sizeId, // 尺码ID
        //                   "skc": cItems.colorId,   // 颜色ID
        //                   "skcName": cItems.colorName,   // SKC名称,必填
        //                   "skuEnName": cItems.colorName, // sku颜色英文名称 ,必填

        //             "colorCategoryId": cItems.parentId || '', // 颜色是父级ID

        //                   "skuDesc":`${cItems.colorName},${sizeObj.name}`, // 紫灰,29

        //                   "skuSaleDesc": `${cItems.colorName},${sizeObj.name}`, // 紫灰,29
        //                   "skuNameDesc": `${that.data.formData.title},${cItems.colorName},${sizeObj.name}`, // "牛仔长裤加厚牛仔长裤,紫灰,29",
        //                   "skuSaleRelate": `${cItems.colorName},${sizeObj.name}`, // "紫灰,29",
        //                   "sizeType": sizeObj.description || '', // "165/72A（29）",
        //                   "sizeName": sizeObj.name || '', // "29",
        //                   // 供货价
        //                   "supplyPrice": that.data.formData.supplyPrice || '',
        //                   "enable":0, // 启用状态，0：启用，1：作废，默认启用 ,必填 默认0
        //                   "isGroup":false, // 是否组合sku ,必填 默认 false
        //                   "isSample":0, // 审版SKU，0：默认否，1：是 ,必填 默认0
        //                   "isSplit":false, // 是否可拆分发 ,必填 默认 false  
        //                   "skuGroupInfoList":[], //  组合sku信息 数组  
        //                   "image":'',

        //               })
        //           });
        //       }); 

        if (that.data.skuList.length <= 0) {
            wx.showToast({
                title: '请先添加尺码和颜色',
                icon: 'none',
                duration: 2000
            })
            return false
        }
        req_param.skuList = that.data.skuList
        const attrListRequired = Object.values(that.data.attrList)
        const attrListRequiredFind = attrListRequired.find(p => p.isMust === 1 && !p.value)
        if (attrListRequiredFind) {
          wx.showToast({
            title: `请${attrListRequiredFind.attributeType === '1' ? '选择' : '输入'}${attrListRequiredFind.attributeName}`,
            icon: 'none',
            duration: 2000
          })
          return
        }
        // 组装 属性
        let attrs = [];
        let attributeValueList = []
        const attrListValues = Object.values(that.data.attrList);
        attrListValues.forEach(item => {
            item.value = item.value || ''
            // 去掉 item 的 attributeValueList 
            delete item.attributeValueList
            attrs.push(item)
            let attributeValueIds = item.value.split(',')
            attributeValueList.push({
                "attributeId": item.attributeId,
                "attributeValueIds": attributeValueIds,
            })
        });
        req_param.attributeValueList = attributeValueList
        req_param.attrList = attrs;
        req_param.attributeValueList = attrs.map(i => {
          if(i.attributeType === "1" ) { // 下拉选择
            return {
              attributeId: i.attributeId,
              attributeValueIds: i.value ? [i.value] : ""
            }
          } else {
            return {
              attributeId: i.attributeId,
              attributeValue: i.value
            }
          }
        }) 
        // 组装 specAttributeInfoList 
        let specAttributeInfoList = []
        let colorSkuAttrInfo = {}
        that.data.skuAttrs.forEach(item => {
            let saName = item.specAttributeCategoryName || ''
            if (saName == '颜色') {
                colorSkuAttrInfo = item
            }
        });

        if (colorSkuAttrInfo.length <= 0) {
            wx.showToast({
                title: '颜色sku错误',
                icon: 'none',
                duration: 2000
            })
            return false
        }

        // 颜色数据
        specAttributeInfoList.push({
            specAttributeCategoryId: colorSkuAttrInfo.specAttributeCategoryId,
            specAttributeCategoryName: colorSkuAttrInfo.specAttributeCategoryName,
            specAttributeId: colorSkuAttrInfo.specAttributeId,
            specAttributeName: colorSkuAttrInfo.specAttributeName,
            isMainSpec: 1,
            specAttributeValueList: specAttributeValueListToColor,
        })
        // 尺码组信息
        let sizeGroupInfo = that.data.sizeGroupInfo
        let sizeGroupSkuAttrInfo = {} // 当前尺码组信息
    
        that.data.skuAttrs.forEach(item => {
            let sacId = item.specAttributeCategoryId || ''
            if (sacId == sizeGroupInfo.id) { // 选中的尺码组的id == 列表里面的尺码组ID
                sizeGroupSkuAttrInfo = item
            }
        });
        // 选中的尺码 cItem 
        let specAttributeValueListToSizeGroup = []
        that.data.selectedSizes.forEach(sizeId => { 
            let sizeObj = that.data.curSizeList.find(item => item.id == sizeId)
            specAttributeValueListToSizeGroup.push({
                convertSourceName: sizeObj.name,
                name: sizeObj.name,
                specAttributeValueId: sizeObj.id,
                description: sizeObj.description || '', // "165/72A（29）",
                pdSpecAttributeCategoryId: that.data.sizeGroupId, // 尺码组ID 规格属性分类ID ,必填 我司规格尺码的父级Id
            })
        });

        specAttributeInfoList.push({
            specAttributeCategoryId: sizeGroupSkuAttrInfo.specAttributeCategoryId,
            specAttributeCategoryName: sizeGroupSkuAttrInfo.specAttributeCategoryName,
            specAttributeId: sizeGroupSkuAttrInfo.specAttributeId,
            specAttributeName: sizeGroupSkuAttrInfo.specAttributeName,
            isMainSpec: 1,
            specAttributeValueList: specAttributeValueListToSizeGroup,
        })
        req_param.specAttributeInfoList = specAttributeInfoList; 
        //   wx.hideLoading();
        // return false
        // 货源
        req_param.baseSourceManagements = that.data.sourceList;
        // 图片
        // req_param.imageList = that.data.uploadFile.map(item => {
        //     return {
        //         "image": item.file_key,
        //         "url": item.file_path,  
        //         "fileName": item.file_key,
        //         "accessoryUrl": item.file_key, 
        //         "imageCategory":that.data.uploadImageInfo.cateId, // 7
        //         "accessoryCategoryCode":that.data.uploadImageInfo.cateId, // 7
        //         "sourceTypeCode": "1", 
        //         "imageType": that.data.uploadImageInfo.labelId, // 16
        //         "imageLabel": that.data.uploadImageInfo.labelId, // 16
        //         "accessoryTypeCode": that.data.uploadImageInfo.labelId, // 16
        //    
        //     }
        // })
        let req_url = '/api/bamboo/pdPublish/styleRelease';
        // if (that.data.template_id > 0) {
        //     req_param.template_id = that.data.template_id;
        //     req_url = 'admin/Template/edit';
        //     req_param.batch_form = {}
        // }
        // 发起请求
        // wx.showModal({ 
        //     title: '提示',
        //     content: '提交成功',
        //     showCancel: false,
        //     complete() {
        //         wx.showToast({ title: "xx" ,icon: 'error' });
        //     }
        // });

        // return false
        const result = common.request_api(req_url, req_param, true);
        result.then(res => { 
            if (res.code == 200) {
                // msg: "归属部门名称不能为空"
                // 向上一级页面传递参数
                // const eventChannel = that.getOpenerEventChannel();
                // eventChannel.emit('changeData', {});
                // 跳转回前一页
                wx.showModal({
                    title: '提示',
                    content: '提交成功',
                    showCancel: false,
                    complete() {
                        wx.navigateBack();
                    }
                });
            } else {

                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                });
                // wx.showToast({
                //     title: res.msg,
                //     icon: 'error',
                //     duration: 3000,
                // });
            }

            // wx.showModal({
            //     title: '提示',
            //     content: res.DiyApiMsg != '' ? res.DiyApiMsg : '提交成功',
            //     showCancel: false,
            //     complete() {
            //         wx.navigateBack();
            //     }
            // });
        }).finally(() => {
            wx.hideLoading();
        });


    },
    // 点击添加图片时
    AddPic: function () {
        const that = this;
        // 选择图片
        wx.chooseMedia({
            count: 9 - (that.data.tempFiles.length),
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            sizeType: ['original', 'compressed'],
            camera: 'back',
            success(res) {
                for (var i = 0; i < res.tempFiles.length; i++) {
                    app.alpha_upload(res.tempFiles[i].tempFilePath).then(upRes => {
                      
                        let uploadFile = that.data.uploadFile;
                        // uploadFile = uploadFile.concat(upRes); 
                        uploadFile.push({
                            "image": upRes.file_key,
                            "url": upRes.file_path,
                            "fileName": upRes.file_key,
                            "accessoryUrl": upRes.file_key,
                            "imageCategory": that.data.uploadImageInfo.cateId, // 7
                            "accessoryCategoryCode": that.data.uploadImageInfo.cateId, // 7
                            "sourceTypeCode": "1",
                            "imageType": that.data.uploadImageInfo.labelId, // 16
                            "imageLabel": that.data.uploadImageInfo.labelId, // 16
                            "accessoryTypeCode": that.data.uploadImageInfo.labelId, // 16
                            "sort": 1,
                        });

                        that.setData({
                            uploadFile: uploadFile
                        }); 
                    })
                }

                // 重设data http://183.6.58.164:20001/api/public/oss/original/uploadFace
                that.setData({
                    tempFiles: that.data.tempFiles.concat(res.tempFiles)
                });

            }
        })
    },

    // 预览图片
    PreViewImg: function (events) {
        onsole.log('预览图片')
        var that = this;
        // 数据下标
        var index = events.currentTarget.dataset.index;
        var path = events.currentTarget.dataset.path;
        var file_arr = [];
        // 取出所有图片的链接
        for (var i = 0; i < that.data.tempFiles.length; i++) {
            file_arr.push(that.data.tempFiles[i].tempFilePath);
        }
        // 调用
        wx.previewImage({
            current: path, // 当前显示图片的http链接
            urls: file_arr // 需要预览的图片http链接列表
        })
    },

    // 删除或调整图片位置
    DeletePic: function (events) { 
        var that = this;
        // 数据下标
        var index = events.currentTarget.dataset.index;
        // 打开操作表
        this.setData({
            deleteActionsheet: true,
            now_action_index: index
        });
    },


    // 分类值变化时
    CateValueChange: function (e) {
        var cate_show_data = this.data.cate_show_data;
        var choose_cate_index_arr = e.detail.value;
        if (cate_show_data[0][choose_cate_index_arr[0]].children == null) {
            wx.showToast({
                title: '分类不完整',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        if (cate_show_data[1][choose_cate_index_arr[1]].children == null) {
            wx.showToast({
                title: '分类不完整',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        var choose_cate_name = cate_show_data[0][choose_cate_index_arr[0]].name + ' - ' + cate_show_data[1][choose_cate_index_arr[1]].name + ' - ' + cate_show_data[2][choose_cate_index_arr[2]].name;
        let choose_cate_id_arr = [cate_show_data[0][choose_cate_index_arr[0]].id, cate_show_data[1][choose_cate_index_arr[1]].id, cate_show_data[2][choose_cate_index_arr[2]].id]
        const categoryId = choose_cate_id_arr[2]
        this.setData({
            choose_cate_id_arr: choose_cate_id_arr,
            choose_cate_index_arr: choose_cate_index_arr,
            [`sel_text.choose_cate_name`]: choose_cate_name,
            [`formData.categoryId`]: categoryId
        });
        // 属性值的下拉数据跟着改变
        this.getCateAttrByCId(categoryId)
        this.loadDetailByCId(categoryId)
        this.getSizeByCId(categoryId)
    },

    // 分类列变化时
    CateColumnChange: function (e) {
        var cate_all_data = this.data.cate_all_data;
        var cate_show_data = this.data.cate_show_data;
        var sel_cate_arr = this.data.sel_cate_arr;
        var index = e.detail.value;
        // 一级分类改变时
        if (e.detail.column == 0) {
            this.data.cate_show_data[1] = cate_all_data[index].children;
            this.data.cate_show_data[2] = cate_all_data[index].children[0].children;
            
            sel_cate_arr = [index, 0, 0];
        }
        // 二级分类改变时
        if (e.detail.column == 1) {
            this.data.cate_show_data[2] = cate_show_data[1][index].children;
            sel_cate_arr[1] = index;
            sel_cate_arr[2] = 0;
        }
        // 三级分类改变时
        if (e.detail.column == 2) {
            sel_cate_arr[2] = index;
        }
        if (this.data.cate_show_data[1] == null || this.data.cate_show_data[2] == null) {
            wx.showToast({
                title: '分类不完整',
                icon: 'none',
                duration: 1500,
            });
            return false;
        } 
        let threeNode = this.data.cate_show_data[2][sel_cate_arr[2]];
        if (threeNode == null) {
            wx.showToast({
                title: '分类不完整',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        // 重新渲染
        this.setData({
            'formData.title': threeNode.name,
            cate_show_data: this.data.cate_show_data,
            sel_cate_arr: sel_cate_arr
        });
    },
    handleColorChange(event) {
      const list = event.detail
      this.setData({
        ["bomFrom.materialColor"]: list[0].label, // 选中的值
        ["selectStrArr.mateColorName"]: list[0].label, // 选中的值
      });
    },
    newHandleClose(e) {
      const name = e.target.dataset.name
      this.setData({
        [name]: false
      })
    },
  showColor (event) {
    console.log(event,'event');
    const index = event.currentTarget.dataset.index
    const item = event.currentTarget.dataset.item
    this.setData({
      colorShow: true,
      rowIndex: index,
      rowItem: item,
    })
  },
  async listTreeColor () {
    const res = await common.request_api('/api/bamboo/sysColor/listTree', {}, false, 'GET');
    if (res.code === 200) {
      const colorSys = []
      res.data.forEach(i => {
        if (i.parentId === "0") {
          delete i.children
          i.items = []
          colorSys.push({ text: i.label, ...i })
        }
      })
      colorSys.forEach(i => {
        res.data.forEach(r => {
          delete r.children
          if (i.id === r.parentId) {
            if (!i.items.some(p => { return p.id === r.id })) {
              i.items.push({ text: r.label, ...r })
            }

          }
        })
      })
      console.log(colorSys,'colorSys')
      this.setData({
        colors: colorSys,
        allColors: colorSys
      })
    } else {
      wx.showToast({
        title: res.msg,
      })
    }
  },
  colorClickNav ({ detail = {} }) {
    this.setData({
      colorMainActiveIndex: detail.index || 0,
    })
  },
  colorCheckedChange (e) {
    console.log(e.detail);
    this.setData({
      colorChecked: e.detail,
    })
  },
  colorClose () {
    this.setData({
      colorShow: false
    })
  },
  colorConfirm () {
    const checkedLabel = []
    let checkedItem = []
console.log(this.data.colorChecked);
    this.data.colors.forEach(i => {
      i.items.forEach(item => {
        // if (this.data.colorChecked.some(p => { return p === item.id })) {
          // checkedLabel.push(item.label)
          // checkedItem.push(item)
        // }
        if (this.data.colorChecked === item.id) {
          checkedLabel.push(item.label)
          checkedItem.push(item)
        }
      })
    })
    checkedItem = checkedItem.map(p => {
      p.colorName = p.name
      p.colorId = p.id
      return {
        ...p
      }
    })
    let colorAtList = this.data.colorAtList
    console.log(this.data.colorAtList);
    const find = checkedItem.find(p => colorAtList.some(o => o.colorId === p.colorId))
    if (find) {
      wx.showToast({
        title: `${find.name}颜色已存在！`,
        icon: 'error',
        duration: 3000
      })
      return 
    }
    const rowIndex =this.data.rowIndex
    if (colorAtList && colorAtList.length > 0 && checkedItem && checkedItem.length === 1) {
      colorAtList[rowIndex].colorId = checkedItem[0].colorId
      colorAtList[rowIndex].colorName = checkedItem[0].colorName
    } else if (colorAtList && colorAtList.length > 0 && checkedItem && checkedItem.length > 1) {
      checkedItem.forEach((item, isIndex) => {
        if(isIndex === 0) {
          colorAtList[rowIndex].colorId = item.colorId
          colorAtList[rowIndex].colorName = item.colorName
        } else {
          colorAtList.push({
            colorName: item.colorName, // 颜色名称
            colorId: item.colorId,
            colorMulIndex: [-1, -1],  
            color: {},
            isDefault: 1,
          })
        }
      })
    }
    this.setData({
      colorShow: false,
      colorAtList: colorAtList
    })
    this.rebuildSkuList()
  },
  searchChange(events) {
    const keywords = events.detail.trim();
    const name = events.currentTarget.dataset.name
    this.setData({
      [name]: keywords,
    });
  },
  onSearch() {
    let dataList = this.data.allColors
    if (!this.data.colorName) {
      this.setData({
        colors: dataList
      })
    } else {
      let itemsWithParent = [];
      dataList.forEach(category => {
        let newItems = category.items.filter(item => item.label.includes(this.data.colorName));
        if (newItems.length > 0) {
          itemsWithParent.push({
            ...category,
            items: newItems
          });
        }
      });
      console.log(itemsWithParent,'itemsWithParent');
      this.setData({
        colors: itemsWithParent
      })
    }
  }
})